package com.excellence.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import com.excellence.staticdata.OSSConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 徐瑞琪
 */
@Slf4j
public class OSSUtil {
    /**
     * @Author 徐瑞琪
     * @Date 2024/4/9 0:55
     * @Description ALiYunOSS对象存储服务
     * @Param 上传文件
     * @Return 文件的网络路径
     * @Since version-1.0
     */
    public static String uploadFileToOss(MultipartFile file) {
        InputStream input = null;
        if (file == null) {
            return null;
        }
        try {
            input = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String originalFileName = file.getOriginalFilename();
        String fileName = null;
        if (originalFileName != null) {
            fileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
        }
        OSS ossClient = new OSSClientBuilder().build(OSSConstants.ENDPOINT, OSSConstants.ACCESS_KEY_ID, OSSConstants.ACCESS_KEY_SECRET);
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(OSSConstants.BUCKET_NAME, fileName, input);
        // 创建PutObject请求。
        ossClient.putObject(putObjectRequest);
        //关闭资源
        ossClient.shutdown();
        String[] split = OSSConstants.ENDPOINT.split("//");
        return split[0] + "//" + OSSConstants.BUCKET_NAME + "." + split[1] + "/" + fileName;
    }
}


